<template>
  <div class="project-detail p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">项目详情</h2>
          <div>
            <el-button type="primary" @click="goToEdit">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">{{ project.name }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag :type="project.type === ProjectType.FRONTEND ? 'success' : 'info'">
              {{ project.type === ProjectType.FRONTEND ? '前端' : '后端' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="项目状态">
            <el-tag :type="getStatusTag(project.status)">
              {{ getStatusName(project.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ project.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ project.updated_at }}</el-descriptions-item>
          <el-descriptions-item label="代码仓库" :span="2">
            <a v-if="project.git_url" :href="project.git_url" target="_blank">{{ project.git_url }}</a>
            <span v-else>--</span>
          </el-descriptions-item>
          <el-descriptions-item label="项目描述" :span="2">
            {{ project.description || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="项目路径" :span="2">
            <div v-if="project.base_path" class="flex items-center">
              <el-button type="primary" link @click="downloadFile(project.base_path)">
                <el-icon><Download /></el-icon>
                下载项目文件
              </el-button>
              <span class="ml-2 text-gray-500">{{ project.base_path.split('/').pop() }}</span>
            </div>
            <span v-else>--</span>
          </el-descriptions-item>
          <el-descriptions-item label="版本" :span="2">
            <div v-if="project.versions && project.versions.length > 0" class="flex flex-col gap-2">
              <div v-for="version in project.versions" :key="version.id" class="flex items-center gap-2">
                <el-tag :type="version.is_current ? 'success' : 'info'" size="small">{{ version.version }}</el-tag>
                <span class="text-gray-500">{{ version.notes }}</span>
                <span class="text-sm text-gray-400">{{ version.created_at }}</span>
              </div>
            </div>
            <span v-else>--</span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="mt-6">
          <h3 class="text-lg font-medium mb-4">部署历史</h3>
          <el-table :data="deployHistory" stripe border>
            <el-table-column prop="id" label="部署ID" width="80" />
            <el-table-column prop="environment" label="环境" width="100">
              <template #default="{ row }">
                <el-tag size="small">{{ row.environment }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getDeployStatusType(row.status)" size="small">
                  {{ getDeployStatusName(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="部署时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" link @click="viewDeployDetail(row.id)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="mt-6 flex justify-center">
          <el-button type="primary" @click="handleDeploy">部署项目</el-button>
          <el-button type="danger" @click="handleDelete">删除项目</el-button>
        </div>
      </div>
    </el-card>

    <!-- 部署对话框 -->
    <el-dialog v-model="deployDialogVisible" title="部署项目" width="500px">
      <el-form :model="deployForm" label-width="100px">
        <el-form-item label="项目名称">
          <span>{{ project.name }}</span>
        </el-form-item>
        <el-form-item label="环境" prop="environment">
          <el-select v-model="deployForm.environment" placeholder="请选择部署环境" class="w-full">
            <el-option label="开发环境" value="development" />
            <el-option label="测试环境" value="testing" />
            <el-option label="生产环境" value="production" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deployDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeploy">确认部署</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { ProjectType, ProjectStatus, DeployStatus, type Project } from '@/model/project-model'
import { getProject, deleteProject, createDeployment, getDeploymentList } from '@/request/project-api'

defineOptions({
  name: 'ProjectDetail'
})

const route = useRoute()
const router = useRouter()
const projectId = route.params.id as string

// 项目数据
const loading = ref(true)
const project = reactive<Project>({
  id: 0, // 改为number类型
  name: '',
  type: ProjectType.FRONTEND,
  status: ProjectStatus.DEVELOPMENT, // 修正为有效的枚举值
  created_at: '', // 修正字段名
  updated_at: '' // 修正字段名
})

// 模拟部署历史数据
const deployHistory = ref([
  {
    id: 'deploy1',
    environment: 'development',
    status: 'success',
    createTime: '2025-07-24 14:30:00'
  },
  {
    id: 'deploy2',
    environment: 'testing',
    status: 'failed',
    createTime: '2025-07-23 10:15:00'
  }
])

// 部署对话框
const deployDialogVisible = ref(false)
const deployForm = reactive({
  environment: 'development',
  versionId: 1 // 添加版本叇字段，默认值为1
})

// 获取项目详情
const fetchProjectDetail = async () => {
  loading.value = true
  try {
    const response = await getProject(Number(projectId)) // 转换为数字类型
    if (response.code === 0) {
      Object.assign(project, response.data)
    } else {
      ElMessage.error(response.errorMsg || '获取项目详情失败')
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

// 下载文件
const downloadFile = (url: string) => {
  if (!url) return
  
  // 在实际项目中，这里应该通过浏览器下载文件
  // 模拟环境中只显示成功消息
  const fileName = url.split('/').pop() || '文件'
  ElMessage.success(`正在下载${fileName}，请稍后...`)
  
  // 在真实环境中，这里会创建一个临时链接触发下载
  // const downloadLink = document.createElement('a')
  // downloadLink.href = url
  // downloadLink.target = '_blank'
  // downloadLink.download = fileName
  // document.body.appendChild(downloadLink)
  // downloadLink.click()
  // document.body.removeChild(downloadLink)
  
  setTimeout(() => {
    ElMessage.success(`${fileName}下载完成！`)
  }, 1500)
}

// 处理部署
const handleDeploy = () => {
  deployDialogVisible.value = true
}

// 确认部署
const confirmDeploy = async () => {
  try {
    // 需要添加versionId参数
    const versionId = deployForm.versionId || 1 // 默认版本或使用选择的版本
    const response = await createDeployment(
      Number(projectId), // 确保是数字类型
      versionId, 
      deployForm.environment
    )
    if (response.code === 0) {
      ElMessage.success('部署成功')
      deployDialogVisible.value = false
      // 实际应用中这里应该刷新部署历史
    } else {
      ElMessage.error(response.errorMsg || '部署失败')
    }
  } catch (error) {
    console.error('部署项目失败:', error)
    ElMessage.error('部署项目失败')
  }
}

// 处理删除
const handleDelete = () => {
  ElMessageBox.confirm(`确认删除项目 "${project.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await deleteProject(Number(projectId)) // 转换为数字类型
        if (response.code === 0) {
          ElMessage.success('删除成功')
          router.push('/project/list')
        } else {
          ElMessage.error(response.errorMsg || '删除失败')
        }
      } catch (error) {
        console.error('删除项目失败:', error)
        ElMessage.error('删除项目失败')
      }
    })
    .catch(() => {
      // 取消删除操作
    })
}

// 获取状态标签类型
const getStatusTag = (status: ProjectStatus) => {
  switch (status) {
    case ProjectStatus.ACTIVE:
      return 'success'
    case ProjectStatus.DEVELOPMENT:
      return 'warning'
    case ProjectStatus.INACTIVE:
      return 'info'
    case ProjectStatus.DEPRECATED:
      return 'danger'
    default:
      return 'info' // 默认返回一个有效的标签类型
  }
}

// 获取状态名称
const getStatusName = (status: ProjectStatus) => {
  switch (status) {
    case ProjectStatus.ACTIVE:
      return '激活'
    case ProjectStatus.DEVELOPMENT:
      return '开发中'
    case ProjectStatus.INACTIVE:
      return '停用'
    case ProjectStatus.DEPRECATED:
      return '废弃'
    default:
      return status
  }
}

// 获取部署状态类型
const getDeployStatusType = (status: string) => {
  switch (status) {
    case 'success':
      return 'success'
    case 'failed':
      return 'danger'
    case 'running':
      return 'warning'
    case 'pending':
      return 'info'
    default:
      return 'info' // 默认返回一个有效的标签类型
  }
}

// 获取部署状态名称
const getDeployStatusName = (status: string) => {
  switch (status) {
    case 'success':
      return '成功'
    case 'failed':
      return '失败'
    case 'running':
      return '进行中'
    case 'pending':
      return '等待中'
    default:
      return status
  }
}

// 查看部署详情
const viewDeployDetail = (deployId: string) => {
  router.push(`/deploy/detail/${deployId}`)
}

// 返回列表页
const goBack = () => {
  router.push('/project/list')
}

// 跳转到编辑页面
const goToEdit = () => {
  router.push(`/project/edit/${projectId}`)
}

onMounted(() => {
  fetchProjectDetail()
})
</script>

<style scoped lang="scss">
.project-detail {
  .el-descriptions {
    margin: 20px 0;
  }
}
</style>
